package com.bawei.lib_net.interceptor

import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import okio.Buffer
import java.nio.charset.StandardCharsets


/**
 * @author yaotianxue
 * @description 签名拦截器：请求体->字符串+密钥盐->md5加密->签名  请求头x-api-sign：签名
 * @date 2025/5/23
 */
class SignInterceptor: Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val newBuilder = request.newBuilder()

        //请求体->字符串
        val json = bodyToString(request)
        val sign = createSign(json, "240111134737B4389719")
        newBuilder.addHeader("x-api-sign", sign)
        return chain.proceed(newBuilder.build())
    }

    fun bodyToString(request: Request): String {
        val buffer = Buffer()
        request.body?.writeTo(buffer)
        return buffer.readUtf8()
    }
    fun createSign(json:String, salt:String):String{
        val buffer = Buffer()
        buffer.write(json.toByteArray(StandardCharsets.UTF_8))
        buffer.write(salt.toByteArray(StandardCharsets.UTF_8))
        //md5加密
        return buffer.md5().hex() //十六进制

    }

}